<template>
  <el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible">

    <el-form
      ref="dataForm"
      :model="dataForm"
      :rules="dataRule"
      label-width="80px"
      @keyup.enter.native="dataFormSubmit()"
    >

      <el-form-item label="部门名称" prop="name">
        <el-input v-model="dataForm.name" placeholder="部门名称" />
      </el-form-item>

      <el-form-item label="上级部门" prop="parentId">
        <el-input v-model="dataForm.parentName" v-popover:deptListPopover :readonly="true" />
        <el-popover ref="deptListPopover" placement="bottom-start" trigger="click">
          <el-tree
            ref="deptListTree"
            :data="deptList"
            :props="listTreeProps"
            node-key="id"
            :default-expand-all="true"
            :highlight-current="true"
            :expand-on-click-node="false"
            @current-change="deptListTreeChangeHandle"
          />
        </el-popover>
      </el-form-item>

      <el-form-item label="排序号" prop="sortValue">
        <el-input-number v-model="dataForm.sortValue" controls-position="right" :min="0" label="排序号" />
      </el-form-item>

      <el-form-item label="负责人" prop="leader">
        <el-select
          v-model="dataForm.leader"
          style="width: 189px;"
          placeholder="请选择负责人"
          clearable
          @change="userSelectorChangeHandle"
        >
          <el-option v-for="user in userList" :key="user.id" :label="user.name" :value="user.name" />
        </el-select>
      </el-form-item>

      <el-form-item label="电话" prop="phone">
        <el-input v-model="dataForm.phone" placeholder="电话" />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-switch
          v-model="dataForm.status"
          active-color="#13ce66"
          inactive-color="#ff4949"
          :inactive-value="0"
          :active-value="1"
        />
      </el-form-item>

    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>

  </el-dialog>
</template>

<script>
import api from '@/api/system/dept'
import userApi from '@/api/system/user'
// 数据转换为树形结构(这个一定要加,不然没有如 'renren-fast-vue'demo中展示的效果)
import { translateTreeData } from '@/utils/index'

export default {
  data() {
    return {
      visible: false,
      dataForm: {
        id: 0,
        name: '',
        parentId: '',
        parentName: '',
        sortValue: '',
        leader: '',
        phone: '',
        status: 1
      },
      // 上级部门信息
      deptList: [],
      // 上级部门el-tree属性
      listTreeProps: {
        label: 'name',
        children: 'children'
      },
      // 用户列表,用于显示负责人
      userList: [],
      // 校验规则
      dataRule: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' }
        ],
        treePath: [
          { required: true, message: '树结构不能为空', trigger: 'blur' }
        ],
        sortValue: [
          { required: true, message: '排序不能为空', trigger: 'blur' }
        ],
        leader: [
          { required: true, message: '负责人不能为空', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '电话不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    init(id) {
      this.dataForm.id = id || 0

      api.getDataListForEdit().then(res => {
        this.deptList = translateTreeData(res.data, 'id')
        this.getUserList()
      }).then(() => {
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
        })
      }).then(() => {
        if (this.dataForm.id) {
          api.getInfoById(id).then(res => {
            this.dataForm.name = res.data.name
            this.dataForm.parentId = res.data.parentId
            this.dataForm.sortValue = res.data.sortValue
            this.dataForm.leader = res.data.leader
            this.dataForm.phone = res.data.phone
            this.dataForm.status = res.data.status

            this.deptListTreeSetCurrentNode()
          })
        } else {
          this.deptListTreeSetCurrentNode()
        }
      })
    },
    // 查询用户列表
    getUserList() {
      userApi.getDataList({
        'page': 1,
        'limit': 500,
        'keyword': ''
      }).then(res => {
        this.userList = res.data.records
      })
    },
    // 下拉框选中值发生变化时触发
    userSelectorChangeHandle(data) {
      for (var i = 0; i <= this.userList.length - 1; i++) {
        if (this.userList[i].name === data) {
          // 当选择某个用户的时候,自动填写对应的手机号
          this.dataForm.phone = this.userList[i].phone
        }
      }
    },
    deptListTreeChangeHandle(data, node) {
      this.dataForm.parentId = data.id
      this.dataForm.parentName = data.name
    },
    // 当选中当前树形节点后,输入框内显示该节点名称
    deptListTreeSetCurrentNode() {
      // setCurrentKey是 el-tree中的属性方法
      this.$refs.deptListTree.setCurrentKey(this.dataForm.parentId)
      // this.$refs.listTree.getCurrentNode() 表示获取选中的节点信息
      this.dataForm.parentName = (this.$refs.deptListTree.getCurrentNode() || {})['name']
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          let treePath = ''
          if (this.dataForm.parentId === 0) {
            treePath = this.dataForm.name
          } else {
            treePath = this.dataForm.parentName + ',' + this.dataForm.name
          }

          api.editData({
            'id': this.dataForm.id || undefined,
            'name': this.dataForm.name,
            'parentId': this.dataForm.parentId,
            'treePath': treePath,
            'sortValue': this.dataForm.sortValue,
            'leader': this.dataForm.leader,
            'phone': this.dataForm.phone,
            'status': this.dataForm.status
          }, !this.dataForm.id ? 'save' : 'update').then(res => {
            this.$message({
              message: res.msg,
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.visible = false
                this.$emit('refreshDataList')
              }
            })
          })
        }
      })
    }
  }
}
</script>
